#!/usr/bin/env bash

DRIVER_PATH="${TRAVIS_BUILD_DIR}/vic/drivers/image/"
DRIVER_EXE="${DRIVER_PATH}vic_image.exe"
SAMPLES_PATH="${TRAVIS_BUILD_DIR}/samples/"

function vic_before_install {
    echo vic_before_install
    echo $PATH
    if [ ! -z "$USE_CC" ]; then
        echo "export CC=$USE_CC"
        export CC=$USE_CC;
        $CC --version
    fi
    if [ "$TRAVIS_OS_NAME" = "osx" ]; then
        echo "Testing on osx"
		if [ ! -z "$BREW_TAPS" ]; then
			for tap in $BREW_TAPS
			do
				brew tap $tap
			done
		fi
        if [ ! -z "$BREW_INSTALLS" ]; then
            brew update
            for pkg in $BREW_INSTALLS
            do
                brew outdated $pkg || brew upgrade $pkg || brew install $pkg
                brew link $pkg
            done
            # building openmpi from source - not sure why the homebrew install
            # isn't working right.
            brew install homebrew/versions/gcc49
            brew reinstall open-mpi --build-from-source
        fi
        export TRAVIS_MPIPATH=/usr/local
        export NC_LIBS=$(/usr/local/bin/nc-config --libs)
        export NC_CFLAGS=$(/usr/local/bin/nc-config --cflags)
    else
		export TRAVIS_MPIPATH="${HOME}/mpich"
        export NC_LIBS=$(/usr/bin/nc-config --libs)
        export NC_CFLAGS=$(/usr/bin/nc-config --cflags)

        # Install MPICH
        if [ ! -d ${TRAVIS_MPIPATH} ]; then
            install_mpich
        else
            echo "MPICH installed..."
        fi
	fi
    export PATH=${TRAVIS_MPIPATH}/bin:${PATH}
    find ${TRAVIS_MPIPATH} -name mpiexec
    mpiexec --version
    find ${TRAVIS_MPIPATH} -name mpicc
    export MPICC="${TRAVIS_MPIPATH}/bin/mpicc"
    $MPICC --version
    echo "NETCDF LIB FLAGS ------> ${NC_LIBS}"
    echo "NETCDF C FLAGS --------> ${NC_CFLAGS}"
}

function vic_install {
    echo vic_install
    cd ${TRAVIS_BUILD_DIR}
    echo $PWD
    make full $EXTENSION -C $DRIVER_PATH
}

function vic_before_script {
    echo vic_before_script
    if [ ! -f $DRIVER_EXE ]; then
        echo "Executable (${DRIVER_EXE}) not found!"
        exit 1
    fi

    echo "Getting sample data"
    bash ${SAMPLES_PATH}/get_sample_data.bash

}

function vic_script {
    echo vic_script
    $DRIVER_EXE -v
    $DRIVER_EXE -o

    # Set the number of OpenMP threads to use
    # https://docs.travis-ci.com/user/languages/c/#OpenMP-projects 
    export OMP_NUM_THREADS=4

    # Run test package
    ./tests/run_tests.py unit examples system \
        --image=${DRIVER_EXE} \
        --data_dir=${SAMPLES_PATH}/data
}

function vic_after_success {
    echo vic_after_success
    echo "Success!"
}

function vic_after_failure {
    echo vic_after_failure
    echo "Test failed -- please review the log"
}
